package com.mrzhou.nio;


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIO 客户端
 */
public class NioClient {

    private static final String SERVER_HOST = "10.130.2.165";
    private static final int SERVER_PORT = 8888;
    private Selector selector;

    public static void main(String[] args) {
        for(int i = 0; i < 2; i++) {
            new Thread(() -> {
                NioClient client = new NioClient();
                client.connect(SERVER_HOST, SERVER_PORT);
                client.listen();
            }).start();
        }
    }

    /**
     * 链接服务器
     * @param host 服务器地址
     * @param port 服务器端口号
     */
    public void connect(String host, int port) {
        try{
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            this.selector = Selector.open();
            sc.register(selector, SelectionKey.OP_CONNECT);
            sc.connect(new InetSocketAddress(host, port)); // 获取NIO服务器链接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void listen() { // 客户端监听服务器的信息
        try{
            while (true) {
                int events = selector.select();
                if(events > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isConnectable()) {
                            SocketChannel channel = (SocketChannel) key.channel();
                            if(channel.isConnectionPending()) {
                                channel.finishConnect();
                            }
                            channel.configureBlocking(false);
                            channel.register(selector, SelectionKey.OP_READ);
                            String msg = "Hello this is " + Thread.currentThread().getName();
                            System.out.println(msg);
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            buffer.put(msg.getBytes());
                            buffer.flip();
                            channel.write(buffer);
                        } else if (key.isReadable()){
                            SocketChannel sc = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            sc.read(buffer);
                            buffer.flip();
                            System.out.println("接收到的服务器消息: " + new String(buffer.array()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
